package com.alogic.html.util;

import com.anysoft.util.Configurable;
import com.anysoft.util.IOTools;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.Settings;
import com.anysoft.util.XMLConfigurable;
import com.anysoft.util.XmlTools;
import com.anysoft.util.resource.ResourceFactory;

import java.io.InputStream;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.alogic.load.Loader;

/**
 * Html tag 管理器
 * @author duanyy
 * @since 1.6.12.27 [20190327 duanyy]
 * 
 * @version 1.6.12.36 [20190611 duanyy] <br>
 * - 重构html文档框架<br>
 */
public class HtmlTagManager extends Loader.Sinkable<HtmlTag> implements Configurable,XMLConfigurable{
	/**
	 * 缺省配置文件地址
	 */
	protected static final String DEFAULT = "java:///com/alogic/html/htmltag.xml#" + HtmlTagManager.class.getName();	
	protected static HtmlTag dftHtmlTag = new HtmlTag();
	protected static HtmlTagManager instance = null;
	
	protected String[] globalAttrs = null;
	
	public String [] getGlobalAttrs(){
		return globalAttrs;
	}
	
	@Override
	public void configure(Properties p){
		super.configure(p);
		globalAttrs = PropertiesConstants.getString(p,
				"globalAttrs", 
				"id,accesskey,class,contenteditable,contextmenu,dir,draggable,dropzone,hidden,lang,spellcheck,style,tabindex,title,translate").split(",");		
	}
	
	public static HtmlTag getHtmlTag(String id){
		HtmlTag found =  getDefault().load(id, true);
		return found == null ? dftHtmlTag:found;
	}
	
	@Override
	protected HtmlTag loadFromSelf(String id, boolean cacheAllowed) {
		return null;
	}
	
	public static HtmlTagManager getDefault(){
		if (instance == null){
			synchronized (HtmlTagManager.class){
				if (instance == null){
					Settings p = Settings.get();
					String master = PropertiesConstants.getString(p, "html.master", DEFAULT);
					String secondary = PropertiesConstants.getString(p, "html.secondary", DEFAULT);
					instance = loadFrom(master,secondary,Settings.getResourceFactory());
				}
			}
		}
		
		return instance;
	}	
	
	public static HtmlTagManager loadFrom(String master,String secondary,ResourceFactory resourceFactory) {
		ResourceFactory rf = resourceFactory;
		if (rf == null){
			rf = Settings.getResourceFactory();
		}
	
		InputStream in = null;
		try {
			in = rf.load(master, secondary, null);
			Document doc = XmlTools.loadFromInputStream(in);
			if (doc != null){
				return loadFrom(doc,Settings.get());
			}
		}catch (Exception ex){
			LOG.error("The config file is not a valid file,url = "
					+ master);			
		}finally{
			IOTools.close(in);
		}
		return null;
	}

	public static HtmlTagManager loadFrom(Document doc,Properties p) {
		return loadFrom(doc.getDocumentElement(),p);
	}

	public static HtmlTagManager loadFrom(Element root,Properties p) {
		HtmlTagManager manager = new HtmlTagManager();		
		manager.configure(root, p);
		return manager;
	}	
}
